import { useAuth } from "../../hooks/useAuth";
import React, { useEffect, useState } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import type {
  IDomEditor,
  IEditorConfig,
  IToolbarConfig,
} from "@wangeditor/editor";
import {
  Button,
  Space,
  Table,
  Tag,
  Modal,
  Form,
  Input,
  Popconfirm,
  message,
} from "antd";
import type { TableProps } from "antd";
import request from "../../axios/request";
import {
  BorderInnerOutlined,
  CheckOutlined,
  FormOutlined,
  VerticalAlignTopOutlined,
} from "@ant-design/icons";
import "@wangeditor/editor/dist/css/style.css";
import { useNavigate } from "react-router-dom";
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
function Index() {
  const [shuju, setshuju] = useState([]);
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "博客标题",
      dataIndex: "title",
      key: "title",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "作者",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "标签",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "大图",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "创造时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "操作栏",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={confirm}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger onClick={() => shanchu(record.id)}>
              <BorderInnerOutlined style={{ color: "red" }} />
            </Button>
          </Popconfirm>

          <button onClick={() => bianji(record)}>
            <FormOutlined />
          </button>
          <button onClick={() => xiangqing(record.id)}>
            详情
          </button>
          <button onClick={() => xiajia(record.id)}>
            下架
            <CheckOutlined style={{ color: "green" }} />
          </button>
        </Space>
      ),
    },
  ];
  const [isModalOpen, setIsModalOpen] = useState(false);

  useAuth();
  const diaoyong = async () => {
    await request.get("/article/list").then((res) => {
      console.log(res);
      if (res.status == 200) {
        setshuju(res.data.rows);
        console.log(res.data.rows);
      }
    });
  };
  useEffect(() => {
    diaoyong();
  }, []);
  // 添加
  const tianjia = async () => {
    await request
      .post("/article", {
        title: "wowowowo",
        content: "sslsllsls",
        authorId: 47529555,
      })
      .then((res) => {
        if(res.status==200){
          diaoyong()
        }
      });
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  // 删除
  const [shanchuid, setshanchuid] = useState();
  const shanchu = (ida) => {
    setshanchuid(ida);
  };
  const xiajia = (ida) => {
    // console.log(id);
    setshuju(shuju.filter((data) => data.id != ida));
  };
  const confirm: PopconfirmProps["onConfirm"] = (e) => {
    message.success("删除成功");
    setshuju(shuju.filter((data) => data.id != shanchuid));
  };

  const cancel: PopconfirmProps["onCancel"] = (e) => {
    message.error("取消删除");
  };
  const [bianjiform] = Form.useForm();
  const [html, setHtml] = useState("");
  const [bianjiid, setbianjiid] = useState("");
  // 编辑
  const bianji = (a) => {
    setbianjiid(a.id);
    bianjiform.setFieldsValue(a);
    console.log(a);
    setIsModalOpen(true);
    setHtml(a.content);
  };
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 编辑器内容

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setTimeout(() => {
      setHtml("<p>hello world</p>");
    }, 1500);
  }, []);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  // editor.getText()
  const handleOk = async () => {
    await request
      .put(`/article/${bianjiid}`, {
        title: bianjiform.getFieldValue("title"),
        content: html,
      })
      .then((res) => {
        // console.log(res);
        if (res.status == 204) {
          diaoyong();
        }
      });

    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

const nav=useNavigate()

  const xiangqing=(aaa)=>{
    // console.log(aaa)
    nav(`/home/liet?id=${aaa}`)
  }

  return (
    <div>
      <Button color="danger" variant="solid" onClick={tianjia}>
        添加
      </Button>
      <Modal
        title="编辑博客对话框"
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        width={1200}
      >
        <Form
          form={bianjiform}
          name="basic"
          layout="inline"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 1200 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="文章标题" name="title">
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="作者" name="zuozhe">
            <Input placeholder="暂无作者" />
          </Form.Item>
          <Form.Item<FieldType> label="标签" name="biaoqian">
            <Input placeholder="暂无标签" />
          </Form.Item>
          <Form.Item<FieldType> label="更新博客大图" name="datu">
            <Input placeholder="暂无加载" />
          </Form.Item>
          <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
              style={{ borderBottom: "1px solid #ccc" }}
            />
            <Editor
              defaultConfig={editorConfig}
              value={html}
              onCreated={setEditor}
              onChange={(editor) => setHtml(editor.getText())}
              mode="default"
              style={{ height: "500px", overflowY: "hidden" }}
            />
          </div>
          <div
            style={{ marginTop: "15px" }}
            dangerouslySetInnerHTML={{ __html: html }}
          ></div>
        </Form>
      </Modal>
      <Table<DataType> columns={columns} dataSource={shuju} />
    </div>
  );
}

export default Index;
